<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use fast\Random;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Exception;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /*导入用户数据*/
    public function importdata()
    {
        if(request()->isPost()){
            $params = $this->request->post('row/a');
            // 解析导入文件
            $filePath = ROOT_PATH . DS . 'public' . DS . $params['file'];
            if (!is_file($filePath)) {
                $this->error('导入失败');
            }
            $fields = ['name','phone',"address","zt_address"];
            $excelData = $this->parseImportFileData($filePath, $fields);
            $time=time();
            $ip=get_client_ip();
            // 保存数据
            $restr="第";
            $j=0;
            $insert = [];
            foreach ($excelData as $k=>$row){
                if(!$row['name'] && !$row['phone']){
                    continue;
                }
                if(!$row['name']){
                    $restr.=($k+1)."、";
                    $j++;
                    continue;
                }
                if(!$row['phone']){
                    $restr.=($k+1)."、";
                    $j++;
                    continue;
                }
                $salt=Random::alnum(4);
                $passkey=Random::alnum(6);
                $userkey=uniqid();
                $password=md5(md5($passkey) . $salt);
                $user=$this->model::get(['mobile'=>$row['phone']]);
                if($user){
                    continue;
                }
                $insert[] = [
                    'nickname' => $row['name'],
                    'username'=>$row['phone'],
                    'mobile'=>$row['phone'],
                    'address'=>$row['address'],
                    'zt_address'=>$row['zt_address'],
                    'salt'=>$salt,
                    'password'=>$password,
                    'jointime'  => $time,
                    'joinip'    => $ip,
                    'logintime' => $time,
                    'loginip'   => $ip,
                    'prevtime'  => $time,
                    'status'    => 'normal',
                    "userkey"=>$userkey,
                    "passkey"=>$passkey,
                ];
            }
            $this->model->saveAll($insert);
            if($j>0){
                $this->error('共'.$j."条数据导入失败,分别是".$restr);
            }
            $this->success("导入成功");
        }else{
            return $this->fetch('import');
        }
    }
    private function parseImportFileData($file, array $fields){
        //实例化reader
        $ext = pathinfo($file, PATHINFO_EXTENSION);
        if (!in_array($ext, ['xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'xls') {
            $reader = IOFactory::createreader('Xls');
        } else {
            $reader = IOFactory::createreader('Xlsx');
        }
        if (!$PHPExcel = $reader->load($file)) {
            $this->error(__('Unknown data format'));
        }
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表

        $sheetData = [];
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行

        $maxColumnNumber = Coordinate::columnIndexFromString($allColumn); // 10 列
        try {
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {

                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    if($val !== ''){
                        $values[] = is_null($val) ? '' : $val;
                    }
                }
                $temp = array_combine($fields, $values);
                if ($temp) {
                    $sheetData[] = $temp;
                }
            }
            return $sheetData;
        }catch (Exception $e){
            $this->error('导入文件失败:'.$e->getMessage());
        }
    }

}
